package com.fgchen.study.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * Created by fgchen on 2017/6/23.
 */
public class CompressUtil {

    public static final Charset UTF8 = Charset.forName("UTF-8");

    /**
     * 以Base64编码字节数组
     * @param datas
     * @return
     */
    public static String base64(byte[] datas) {
        return new BASE64Encoder().encode(datas);
    }

    /**
     * 以Base64解码字符串
     * @param str
     * @return
     * @throws IOException
     */
    public static byte[] unbase64(String str) throws IOException {
        return new BASE64Decoder().decodeBuffer(str);
    }

    /**
     * 以GZIP压缩字节数组
     * @param datas
     * @return
     * @throws IOException
     */
    public static byte[] gzip(byte[] datas) throws IOException {
        ByteArrayInputStream bais = new ByteArrayInputStream(datas);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        GZIPOutputStream gos = new GZIPOutputStream(baos);
        byte[] buf = new byte[1024];
        for (int len = 0; (len = bais.read(buf)) > 0;) {
            gos.write(buf, 0, len);
        }
        gos.close();
        bais.close();
        return baos.toByteArray();
    }

    /**
     * 以GZIP解压字节数组
     * @param datas
     * @return
     * @throws IOException
     */
    public static byte[] ungzip(byte[] datas) throws IOException {
        GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(datas));
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        for (int len = 0; ((len = gis.read(buf)) > 0);) {
            baos.write(buf, 0, len);
        }
        baos.close();
        gis.close();
        return baos.toByteArray();
    }
}
